<template>
  <div :class="[ns.b()]">
    <el-form ref="formRef" :label-width="labelWidth" :label-position="labelPosition" :model="searchConfig.fields">
      <el-row :gutter="gutter">
        <el-col v-for="item in searchConfig.control" :key="item.field" :span="item.col || 24">
          <el-form-item :label="renderLable(item.label)" :prop="item.field" :rules="item.rules">
            <component ref="controlRef" v-model:value="searchConfig.fields[item.field]" :is="modules[item.type]" :config="item" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div @click="checkForm">校验</div>
  </div>
</template>
<script lang="ts">
  export default { name: 'FormIndex' }
</script>
<script setup lang="ts">
  import { useUamespace } from '@/hooks/use-namesapce'

  import type { FormControlsInterface, EmitsInterface } from './types/props'
  // from
  import type { FormInstance } from 'element-plus'
  const props = withDefaults(defineProps<FormControlsInterface>(), {
    colon: () => true,
    gutter: () => 42,
    labelPosition: () => 'right',
  })
  const emit = defineEmits<EmitsInterface>()
  const ns = useUamespace('form-wrap')
  /**
   * ref
   */
  const formRef = ref<FormInstance>()
  const controlRef = ref(null)
  /**
   * 渲染label
   */
  const renderLable = (label: string) => {
    return `${label}${props.colon ? '：' : ''}`
  }
  /**
   * 异步导入（按需加载，推荐）
   */
  const modules = ref({})
  const loadModule = async () => {
    props.searchConfig.control.forEach(async (control) => {
      import(`./../${control.type}/index.vue`).then((res) => {
        // console.log('res', res.default)
        modules.value[control.type] = res.default
      })
      // const type = control.type
      // for (const key in modules) {
      //   if (key.indexOf(type) !== -1) {
      //     const module = await modules[key]()
      //     abc.value[type] = module.default
      //   }
      // }
    })
  }
  loadModule()

  /**
   * 校验
   */
  const checkForm = () => {
    return new Promise<void>((resolve, reject) => {
      formRef.value
        .validate()
        .then(() => {
          resolve()
        })
        .catch(() => {
          reject()
        })
    })
  }

  defineExpose({ checkForm })
</script>
<style lang="scss" scoped>
  @include b(form-wrap) {
    overflow: hidden;
  }
</style>
